/**
* @program: src
*
* @description:通过token发送信息给客户端
*
* @author: Mr.chen
*
* @create: 2020-11-11 13:46
**/
package sendtouser

import (
	"ydd-im/service/api/services/wsservice/account"
	"ydd-im/service/api/services/wsservice/client"
	"ydd-im/service/api/services/wsservice/message"
	"ydd-im/service/api/tools/bind"
	"ydd-im/service/api/tools/response"
	"ydd-im/service/api/tools/util"
	"github.com/gin-gonic/gin"
	//"github.com/go-playground/validator/v10"
	"strconv"
	"sync"

)

type Controller struct {
}
type inputData struct {
	TouserId    int    `json:"touserid" form:"touserid" binding:"required" `
	Media       int    `json:"media" form:"media" `
	Pic         string `json:"pic" form:"pic"`
	Url         string `json:"url" form:"url"  `
	Memo        string `json:"memo" form:"memo" `
	Data        string `json:"data" form:"data" `
}
type inputUsersData struct {
	TouserIds []int  `json:"touserids" form:"touserids[]" binding:"required" `
	Media       int    `json:"media" form:"media" `
	Pic         string `json:"pic" form:"pic"`
	Url         string `json:"url" form:"url"  `
	Memo        string `json:"memo" form:"memo" `
	Data        string `json:"data" form:"data" `
}

// 发送单个用户
func (r *Controller) SendtoUser(c *gin.Context) {
	var inputData inputData
	_, err := bind.Bind(&inputData, c)
	if err != nil {
		response.ResponseJsonFail(c, response.Response{
			Code:    response.ErrorCode,
			Message: "参数有误，请重试",
		})
		return
	}
	if inputData.Media < 0 {
		inputData.Media = 1
	}
	// 获取token查询的用户信息
	userInfo, err := account.GetMiddleUserInfo(c)
	if  err != nil {
		response.ResponseJsonFail(c, response.Response{
			Code:    response.ErrorCode,
			Message: err.Error(),
		})
		return
	}

	//发送信息,这里就全部采用推送的方式，在线的都推送
	var TouserIds []int
	var wg sync.WaitGroup
	var messageList []map[string]string
	TouserIds = append(TouserIds, userInfo.Id, inputData.TouserId)
	TouserIds = util.RemoveRepByMap(TouserIds)
	// 记录消息
	createTime := util.GetCurrentDateTime()
	messageLogId,err :=message.AddMessage(TouserIds,userInfo.Id,1,inputData.TouserId,inputData.Media,inputData.Data,inputData.Pic,inputData.Url,inputData.Memo,createTime)
	if err != nil {
		response.ResponseJsonFail(c, response.Response{
			Code:    response.ErrorCode,
			Message: err.Error(),
		})
		return
	}
	touserIdsCount := len(TouserIds)
	messageListChan := make(chan map[string]string, touserIdsCount)
	wg.Add(touserIdsCount)
	for _, touserId := range TouserIds {
		// 构建消息体
		messageData := response.MessageData{
			MessageLogId:messageLogId,
			ToUserId:touserId,
			Media:inputData.Media,
			Pic:inputData.Pic,
			Url:inputData.Url,
			MessageType:1,
			SendTime:util.GetTimeDate(createTime),
			Content:inputData.Data,
			SendUserId:userInfo.Id,
			SendUsername:userInfo.Username,
			Dstid:inputData.TouserId,
		}
		go func(touserId int, sendUserId int, code int, msg string,messageData response.MessageData) {
			messageId := client.SendMessageToUserAndMine(touserId, sendUserId, code, msg, messageData)
			var messageList map[string]string = make(map[string]string, 0)
			messageList["messageId"] = messageId
			messageList["touserId"] = strconv.Itoa(touserId)
			messageList["sendUserId"] = strconv.Itoa(sendUserId)
			messageListChan <- messageList
			wg.Done()
		}(touserId, userInfo.Id, response.SuccessCode, "Ok",messageData)
	}
	wg.Wait()
	for i := 1; i <= touserIdsCount; i++ {
		list, ok := <-messageListChan
		if ok {
			messageList = append(messageList, list)
		} else {
			return
		}
	}
	close(messageListChan)
	//messageId := client.SendMessageToUser(inputData.TouserId, userInfo.Id, inputData.Code, inputData.Msg, &inputData.Data)
	//response.ResponseJsonOk(c, response.Response{
	//	Code:  response.SuccessCode,
	//	Message: "success",
	//	Data: map[string]string{
	//		"messageId": messageId,
	//	},
	//})

	response.ResponseJsonOk(c, response.Response{
		Code:    response.SuccessCode,
		Message: "success",
		Data:    messageList,
	})
	return
}

// 发送多个用户
func (r *Controller) SendtoUsers(c *gin.Context) {
	var inputUsersData inputUsersData
	_, err := bind.Bind(&inputUsersData, c)
	if err != nil {
		response.ResponseJsonFail(c, response.Response{
			Code:    response.ErrorCode,
			Message: "参数有误，请重试",
		})
		return
	}
	// 参数验证
	//validate := validator.New()
	//// 注册自定义验证
	////_ = validate.RegisterValidation("NameValid", param_verify.NameValid)
	//if err = validate.Struct(s); err != nil {
	//	response.ResponseJsonFail(c, response.Response{
	//		Code:    response.ErrorCode,
	//		Message: err.Error(),
	//	})
	//	return
	//}
	// 获取token查询的用户信息
	userInfo, err := account.GetMiddleUserInfo(c)
	if  err != nil {
		response.ResponseJsonFail(c, response.Response{
			Code:    response.ErrorCode,
			Message: err.Error(),
		})
		return
	}

	if inputUsersData.Media <=0 {
		inputUsersData.Media = 1
	}
	createTime := util.GetCurrentDateTime()

	//发送信息,这里就全部采用推送的方式，在线的都推送
	inputUsersData.TouserIds = append(inputUsersData.TouserIds, userInfo.Id)
	inputUsersData.TouserIds = util.RemoveRepByMap(inputUsersData.TouserIds)
	touserIdsCount := len(inputUsersData.TouserIds)
	messageListChan := make(chan map[string]string, touserIdsCount)
	var wg sync.WaitGroup
	var messageList []map[string]string
	wg.Add(touserIdsCount)
	messageLogId,err :=message.AddMessage(inputUsersData.TouserIds,userInfo.Id,1,0,inputUsersData.Media,inputUsersData.Data,inputUsersData.Pic,inputUsersData.Url,inputUsersData.Memo,createTime)
	if err != nil {
		response.ResponseJsonFail(c, response.Response{
			Code:    response.ErrorCode,
			Message: err.Error(),
		})
		return
	}
	for _, touserId := range inputUsersData.TouserIds {
		// 构建消息体
		messageData := response.MessageData{
			MessageLogId:messageLogId,
			ToUserId:touserId,
			Media:inputUsersData.Media,
			Pic:inputUsersData.Pic,
			Url:inputUsersData.Url,
			MessageType:1,
			SendTime:util.GetTimeDate(createTime),
			Content:inputUsersData.Data,
			SendUserId:userInfo.Id,
			SendUsername:userInfo.Username,
			Dstid:0,
		}
		go func(touserId int, sendUserId int, code int, msg string,messageData response.MessageData) {
			// 记录消息
			messageId := client.SendMessageToUserAndMine(touserId, sendUserId, code, msg, messageData)
			var messageList map[string]string = make(map[string]string, 0)
			messageList["messageId"] = messageId
			messageList["touserId"] = strconv.Itoa(touserId)
			messageList["sendUserId"] = strconv.Itoa(sendUserId)
			messageListChan <- messageList
			wg.Done()
		}(touserId, userInfo.Id, response.SuccessCode, "Ok",messageData )

	}
	wg.Wait()
	for i := 1; i <= touserIdsCount; i++ {
		list, ok := <-messageListChan
		if ok {
			messageList = append(messageList, list)
		} else {
			return
		}
	}
	close(messageListChan)
	response.ResponseJsonOk(c, response.Response{
		Code:    response.SuccessCode,
		Message: "success",
		Data:    messageList,
	})
	return
}
